package com.lyj.stuelasticsearch.service;

import com.lyj.stuelasticsearch.entity.Product;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductSearchService {

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    // 多字段搜索
    public List<Product> searchInMultipleFields(String query) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(query, "name", "description"))
                .build();

        SearchHits<Product> productHits = elasticsearchOperations.search(searchQuery, Product.class);
        return productHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
    }

//    // 聚合查询
//    public List<String> getCategoriesWithCount() {
//        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
//                .addAggregation(AggregationBuilders.terms("categories").field("category"))
//                .build();
//
//        SearchHits<Product> productHits = elasticsearchOperations.search(searchQuery, Product.class);
//        StringTerms categories = productHits.getAggregations().get("categories");
//        return categories.getBuckets().stream()
//                .map(b -> b.getKeyAsString() + " (" + b.getDocCount() + ")")
//                .collect(Collectors.toList());
//    }
}